package com.antifly.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.antifly.common.exception.bizException.BillExceptionCodeEnum;
import com.antifly.common.exception.bizException.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LuoJiaHui
 * @date 2023/1/9 15:29
 * @description
 */
public class CustomDataListener<T> implements ReadListener<T> {

    private Logger logger = LoggerFactory.getLogger(CustomDataListener.class);
    private List<T> data = new ArrayList<>();

    /**
     * 正文起始行
     */
    private Integer headRowNumber;
    /**
     * 合并单元格
     */
    private List<CellExtra> extraMergeInfoList = new ArrayList<>();

    public CustomDataListener(Integer headRowNumber) {
        this.headRowNumber = headRowNumber;
    }

    public List<CellExtra> getExtraMergeInfoList() {
        return extraMergeInfoList;
    }

    public List<T> getData() {
        return data;
    }

    /**
     * When analysis one row trigger invoke function.
     *
     * @param module  one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context analysis context
     */
    @Override
    public void invoke(T module, AnalysisContext context) {
        data.add(module);
    }

    /**
     * if have something to do after all analysis
     *
     * @param context analysis context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        logger.info("所有数据解析完成！");
    }

    /**
     * The current method is called when extra information is returned
     *
     * @param extra   extra information
     * @param context analysis context
     */
    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        switch (extra.getType()) {
            case COMMENT:
            case HYPERLINK: {
                break;
            }
            case MERGE: {
                if (extra.getRowIndex() >= headRowNumber) {
                    extraMergeInfoList.add(extra);
                }
                break;
            }
            default:
                throw new BizException(BillExceptionCodeEnum.EXCEL_MERGE_ERROR);
        }
    }
}
